import {Component, OnInit} from "@angular/core";
import {Router, ActivatedRoute} from "@angular/router";
import {ThemesService} from "../themes.service";
import {Theme} from "../theme";
import {MsgResult} from "../../../../models/msg-result";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../../util/page-subject";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {ResponseUtil} from "../../../../util/response-util";
import {MsgConstants} from "../../../../constants/constants";
import {FormGroup, FormBuilder, Validators} from "@angular/forms";

@Component({
  selector: 'app-theme-update',
  templateUrl: './theme-update.component.html'
})
export class ThemeUpdateComponent implements OnInit {

  theme: Theme;

  themeForm: FormGroup;

  enableValue:string = "0";
  defaultCtrl;
  enableCtrl;

  constructor(private fb: FormBuilder,
              private router: Router,
              private route: ActivatedRoute,
              private themesService: ThemesService,
              private dialogService: OneDialogService,
              private response: ResponseUtil,
              private pageSubject: PageSubject) {

  }
  ngOnInit() {
    this.pushPage();
    //初始化修改表单
    this.initObject();
    //更新表单数据
    this.initUpdateFrom()
  }

  /**
   * 构造表单
   */
  buildForm(): void {
    this.themeForm = this.fb.group({
      'id': [this.theme.id],
      'name': [this.theme.name,[
        Validators.required,
        Validators.maxLength(10)
      ]],
      'code': [this.theme.code,[
        Validators.required,
        Validators.maxLength(20),
        Validators.pattern(/^[a-z\-]+$/)
      ]],
      'isEnable': [this.theme.isEnable],
      'isDefault': [this.theme.isDefault]
    });

    this.themeForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }
  /**
   * isDefault字段改变
   */
  defaultChange(){
    this.defaultCtrl= this.themeForm.controls.isDefault;
    this.enableCtrl= this.themeForm.controls.isEnable;
    this.defaultCtrl.valueChanges.subscribe(
      data => this.onDefaultChange(data)
    );
  }
  onDefaultChange(data){
    if(data == "1"){
      this.enableValue = "1";
      this.theme.isEnable = "1";
      this.enableCtrl.reset({value:"1",disabled:true});
    }else if(data == "0"){
      this.enableValue = this.theme.isEnable || this.enableCtrl.value.value;
      this.enableCtrl.reset({value : this.enableValue,disabled:false});
    }
  }
  /**
   * 值变化监听
   * @param data
   */
  onValueChanged(data?: any) {
    if (!this.themeForm) {
      return;
    }
    const form = this.themeForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }

  }

  /**
   * 校验字段
   * @type {{name: string; code: string}}
   */
  formErrors = {
    'name': '',
    'code': ''
  };
  /**
   * 校验提示信息
   * @type {{name: {required: string; maxlength: string}; code: {required: string; maxlength: string; pattern: string}}}
   */
  validationMessages = {
    'name': {
      'required': '主题不能为空',
      'maxlength': '长度不能超过10',
    },
    'code': {
      'required': '主题编码不能为空',
      'maxlength': '长度不能超过20',
      'pattern': '只能由小写字母或中划线组成.eg:red-light'
    }
  };

  /**
   * 面包屑
   */
  private pushPage() {
    let path = new Path("权限系统", "");
    this.pageSubject.pushPage("主题管理", "修改", path);
  }

  /**
   * 通过id查询
   */
  initUpdateFrom() {
    //获取路由参数
    let id = this.route.snapshot.params["themeId"];
    this.themesService.getThemeById(id).subscribe(
      result => this.response.success(result, this.processGetResult),
      error => this.response.error(error)
    );
  }


  /**
   * 保存修改
   */
  onSubmit() {
    console.log(this.themeForm.value);
    if(!this.themeForm.value.hasOwnProperty("isEnable")){
      let enableValue = this.theme.isEnable || this.enableCtrl.value.value;
      this.enableCtrl.reset({value : enableValue,disabled:false});
    }
    this.theme = this.themeForm.value;
    console.log(this.theme);
    this.themesService.updateTheme(this.theme).subscribe(
      result => this.response.success(result, this.processUpdateResult),
      error => this.response.error(error)
    );
  }

  /**
   * 取消修改
   */
  cancel() {
    this.router.navigate(['..'], {relativeTo: this.route});
  }

  /**
   * id查询成功后调用
   * @param json
   */
  private processGetResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.theme = result.data;
      this.themeForm.patchValue(this.theme);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 修改成功后调用
   * @param json
   */
  private processUpdateResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message, () => this.cancel());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }


  /**
   * 实例化对象
   */
  private initObject() {
    this.theme = new Theme("", "", "", "0", "0");
    this.buildForm();
    this.defaultChange();
  }


}
